package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.mapper.*;
import com.neudu.yiyang.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
public class NurseRecordsController {

    @Autowired
    private NursecontentMapper nursecontentMapper;

    @Autowired
    private NurserecordMapper nurserecordMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private JSONReturn jsonReturn;

    // 查询所有护理记录（带分页和条件查询）
    @PostMapping("/get_all_records")
    public String getAll(@RequestBody Map<String, Object> params) {
        try {
            int pageNum = params.get("pageNum") == null ? 1 : (int) params.get("pageNum");
            int pageSize = params.get("pageSize") == null ? 10 : (int) params.get("pageSize");
            String customerName = (String) params.get("customerName");

            PageHelper.startPage(pageNum, pageSize);

            LambdaQueryWrapper<Nurserecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Nurserecord::getIsDeleted, 0); // 只查询未删除的记录

            List<Nurserecord> list = nurserecordMapper.selectList(queryWrapper);

            // 关联查询客户信息并过滤
            list = list.stream().filter(record -> {
                if (record.getCustomerId() != null) {
                    Customer customer = customerMapper.selectById(record.getCustomerId());
                    record.setCustomer(customer);
                    // 如果传入了customerName，则进行过滤
                    return customerName == null ||
                            customer.getCustomerName().contains(customerName);
                }
                return customerName == null; // 如果没有客户信息，且传入了customerName则过滤掉
            }).collect(Collectors.toList());

            PageInfo<Nurserecord> pageInfo = new PageInfo<>(list);

            Map<String, Object> result = new HashMap<>();
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());

            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询失败: " + e.getMessage());
        }
    }
    // 新增一条护理记录
    @PostMapping("/add_one_record")
    public String addOne(@RequestBody Nurserecord nurserecord) {
        try {
            // 设置默认值
            if (nurserecord.getIsDeleted() == null) {
                nurserecord.setIsDeleted(0); // 默认未删除
            }
            if (nurserecord.getNursingTime() == null) {
                nurserecord.setNursingTime(new Date()); // 默认当前时间
            }
            if (nurserecord.getNursingCount() == null) {
                nurserecord.setNursingCount(1); // 默认1次
            }

            int result = nurserecordMapper.insert(nurserecord);
            return result > 0 ? jsonReturn.returnSuccess("添加成功") : jsonReturn.returnError("添加失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("添加失败: " + e.getMessage());
        }
    }

    // 修改一条护理记录
    @PutMapping("/modify_record_by_id")
    public String modifyById(@RequestBody Nurserecord nurserecord) {
        try {
            if (nurserecord.getId() == null) {
                return jsonReturn.returnError("ID不能为空");
            }

            int result = nurserecordMapper.updateById(nurserecord);
            return result > 0 ? jsonReturn.returnSuccess() : jsonReturn.returnError("更新失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("更新失败: " + e.getMessage());
        }
    }

    // 删除一条护理记录（逻辑删除）
    @DeleteMapping("/remove_record_by_id")
    public String removeById(@RequestParam("id") Integer id) {
        try {
            if (id == null) {
                return jsonReturn.returnError("ID不能为空");
            }

            Nurserecord record = new Nurserecord();
            record.setId(id);
            record.setIsDeleted(1); // 设置为已删除

            int result = nurserecordMapper.updateById(record);
            return result > 0 ? jsonReturn.returnSuccess() : jsonReturn.returnError("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("删除失败: " + e.getMessage());
        }
    }

    // 根据客户ID查询护理记录
    @GetMapping("/get_records_by_customer")
    public String getByCustomerId(@RequestParam("customerId") Integer customerId) {
        try {
            if (customerId == null) {
                return jsonReturn.returnError("客户ID不能为空");
            }

            LambdaQueryWrapper<Nurserecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Nurserecord::getCustomerId, customerId)
                    .eq(Nurserecord::getIsDeleted, 0)
                    .orderByDesc(Nurserecord::getNursingTime);

            List<Nurserecord> records = nurserecordMapper.selectList(queryWrapper);

            // 关联查询客户信息
            records.forEach(record -> {
                if (record.getCustomerId() != null) {
                    Customer customer = customerMapper.selectById(record.getCustomerId());
                    record.setCustomer(customer); // 设置客户信息
                }
            });

            return jsonReturn.returnSuccess(records);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询失败: " + e.getMessage());
        }
    }
    // 查询所有护理项目
    @GetMapping("/get_all_items")
    public String getAllNursingItems(@RequestBody(required = false) Map<String, Object> params) {
        try {
            int pageNum = params != null && params.get("pageNum") != null ? (int) params.get("pageNum") : 1;
            int pageSize = params != null && params.get("pageSize") != null ? (int) params.get("pageSize") : 10;
            String nursingName = params != null ? (String) params.get("nursingName") : null;

            PageHelper.startPage(pageNum, pageSize);

            LambdaQueryWrapper<Nursecontent> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Nursecontent::getIsDeleted, 0); // 只查询未删除的项目

            if (StringUtils.hasText(nursingName)) {
                queryWrapper.like(Nursecontent::getNursingName, nursingName);
            }

            // 确保正确调用实例方法
            List<Nursecontent> items = nursecontentMapper.selectList(queryWrapper);
            PageInfo<Nursecontent> pageInfo = new PageInfo<>(items);

            Map<String, Object> result = new HashMap<>();
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());

            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询护理项目失败: " + e.getMessage());
        }
    }
    @GetMapping("/get_all_customers")
    public String getAllCustomers() {
        try {
            LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Customer::getIsDeleted, 0);
            List<Customer> customers = customerMapper.selectList(wrapper);
            return jsonReturn.returnSuccess(customers);
        } catch (Exception e) {
            return jsonReturn.returnError("查询客户失败: " + e.getMessage());
        }
    }
}